const app = getApp();
const api = require('../../utils/api');
const util = require('../../utils/util');
const Page = require('../../utils/pageProxy');

var animation1 = {};
var animation2 = {};
var adsAnimation = {};
var restartAnimation = '';
var count = 0;

Page({
    loginRequired: true,
    data: {
        navBarHeight: 0,

        shopId: '',
        shopDetail: '', //店铺详情
        bannerList: [],
        isCustomStyle: false, //是否使用自定义背景模版
        floatAdsList: [], //底部浮动广告列表
        floatAdsContent: '', //广告滚动显示内容
        floatAdsAnimation: {}, //广告滚动显示内容的动画效果
        isShowFloatAds: false, //是否显示浮动广告位

        hasStore: '', //是否已经选择店铺
        noSwitchShop: '', //是否显示切换店铺按钮

        baseDistance: 0, //用于计算的基准距离
        scrollLeft: 0, //滚动距离
        firstCategoryList: [], //一级分类
        firstCategoryIndex: -1, //一级分类当前项

        secondCategoryList: [], //二级分类
        secondCategoryIndex: -1, //二级分类当前项
        secondCategoryId: 0, //二级分类id

        productList: [], //商品列表
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false,
        isFinished: false, //加载结束
        isLoading: false, //加载中

        currentItem: {}, //当前操作项
        currentItemIndex: 0, //当前操作项下标
        productDesc: '', //商品描述

        shopcartList: [], //购物车列表
        shopcartListForRecord: [], //用于记录的购物车列表
        shopcartNumber: 0, //购物车商品数量

        firstCategoryAnimation: {}, //全部一级分类弹窗的动画效果
        isShowAllFirstCategory: false,
        productDetailAnimation: {}, //商品详情弹窗的动画效果
        isShowProductDetail: false,
        isShowLayer: false, //弹窗遮罩层

        isPreview: false,
    },
    onLoad(options) {
        if(options.id) {
            wx.setStorageSync('shopId', options.id); //缓存店铺id
            this.setData({
                shopId: options.id,
                noSwitchShop: options.dir ? true : false
            });
        } else if(options.scene) { //读取二维码传值
            wx.setStorageSync('shopId', options.scene); //缓存店铺id
            this.setData({
                shopId: options.scene,
                noSwitchShop: false
            });
        } else if(wx.getStorageSync('shopId')) { //读取缓存店铺id
            this.setData({
                shopId: wx.getStorageSync('shopId')
            });
        }

        this.initData();

        //设置微信分享功能：可分享小程序和分享朋友圈
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },
    onShow() {
        if(app.globalData.isRefreshCategory) {
            app.globalData.isRefreshCategory = false;

            this.setData({
                shopId: wx.getStorageSync('shopId')
            });
            this.initData();
        }
        if(app.globalData.isRefreshShopcart) {
            app.globalData.isRefreshShopcart = false;
            this.getShopcartList();
        }

        //初始化动画
        animation1 = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
        animation2 = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
    },
    unLoad() {
        if(this.data.isShowFloatAds) {
            clearInterval(restartAnimation);
        }
    },

    initData() { //初始化页面数据
        this.setData({
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        
        this.getStoreInfo();
        this.getShopcartList();
    },
    getStoreInfo() { //获取店铺信息
        api.post('/shop/detail?shopId=' + this.data.shopId)
            .then(res => {
                this.setData({
                    shopDetail: res,
                    isCustomStyle: res.businessType == 1 ? true : false,
                });

                if(this.data.isCustomStyle) {
                    this.getBannerList();
                    this.getFloatAdsList();
                }
            })
            .catch(err => {
                if(err.code === '200022' || err.code == '100004') {
                    setTimeout(() => {
                        this.setData({
                            hasStore: false
                        });
                    }, 1000);
                }
            })
    },
    getBannerList() { //获取banner列表
        api.post(`/ad/ad/list?districtCode=0&moduleNo=shop-index&shopId=${this.data.shopId}`)
            .then(res => {
                this.setData({
                    bannerList: res
                });
            })
    },
    getFloatAdsList() { //获取底部广告位列表
        api.post(`/ad/ad/list?districtCode=0&moduleNo=shop-floating&shopId=${this.data.shopId}`)
            .then(res => {
                this.setData({
                    floatAdsList: res,
                    floatAdsContent: res.length ? res[0].title : '',
                    isShowFloatAds: res.length ? true : false,
                });

                if(this.data.isShowFloatAds) {
                    setTimeout(() => {
                        //初始化广告位动画
                        let time = this.data.floatAdsContent.length * 200;
                        adsAnimation = wx.createAnimation({
                            duration: time,
                            timingFunction: 'linear',
                        });
                        //设置并开始动画效果
                        this.startAdsAnimation();
                        //循环动画
                        restartAnimation = setInterval(() => {
                            this.startAdsAnimation();
                        }, time + 2000);
                    }, 2000);
                }
            })
    },
    startAdsAnimation() { //底部广告位动画效果
        // 偏移距离为广告内容的长度*字体大小（若字体大小使用rpx需要换算成px）
        adsAnimation.translateX(-Number(this.data.floatAdsContent.length * 15 + 100)).step();
        adsAnimation.translateX(0).step({duration: 0});
        this.setData({
            floatAdsAnimation: adsAnimation.export(),
        });
    },

    viewBannerDetail(e) { //查看广告详情
        let item = e.currentTarget.dataset.item;
        let type = item.targetType;

        if(type == 1) { //跳转小程序指定页面
            wx.navigateTo({
                url: item.frontRoutePath + '&dir=1'
            });
        } else if(type == 3) { //跳转外部小程序
            let appId = item.apiUrl;
            let path = item.frontRoutePath;
            wx.navigateToMiniProgram({
                appId: appId,
                path: path,
                success: res => {
                    console.log('打开成功')
                }
            });
        } else { //默认页面或者公众号页面
            wx.navigateTo({
                url: '/pages/adsDetail/adsDetail?id=' + item.id
            });
        }
    },
    viewFloatAdsDetail() { //查看底部浮动广告详情
        let item = this.data.floatAdsList[0];
        let type = item.targetType;

        if(type == 1) { //跳转小程序指定页面
            wx.navigateTo({
                url: item.frontRoutePath + '&dir=1'
            });
        } else if(type == 3) { //跳转外部小程序
            let appId = item.apiUrl;
            let path = item.frontRoutePath;
            wx.navigateToMiniProgram({
                appId: appId,
                path: path,
                success: res => {
                    console.log('打开成功')
                }
            });
        } else { //默认页面或者公众号页面
            wx.navigateTo({
                url: '/pages/adsDetail/adsDetail?id=' + item.id
            });
        }
    },

    getShopcartList() { //获取购物车列表
        api.post('/order/cart/list')
            .then(res => {
                let list = res;
                let recordList = [];

                if(this.data.shopId) { //有店铺id的情况，只保存当前店铺的购物车
                    list.forEach(item => {
                        if(item.shopId == this.data.shopId) {
                            item.detailList.forEach(pro => {
                                recordList.push({
                                    id: pro.id,
                                    skuId: pro.productSkuSaleId,
                                    quantity: pro.quantity
                                })
                            })
                        }
                    });
                } else { //没店铺id，全部保存
                    list.forEach(item => {
                        item.detailList.forEach(pro => {
                            recordList.push({
                                id: pro.id,
                                skuId: pro.productSkuSaleId,
                                quantity: pro.quantity
                            })
                        })
                    });
                }
                
                this.setData({
                    shopcartList: list,
                    shopcartListForRecord: recordList,
                });

                this.dealShopcartSummary(0, 1);
                this.getFirstCategory();
            })
    },
    refreshShopcart() { //更新购物车列表
        api.post('/order/cart/list')
            .then(res => {
                let list = res;
                let recordList = [];

                if(this.data.shopId) { //有店铺id的情况，只保存当前店铺的购物车
                    list.forEach(item => {
                        if(item.shopId == this.data.shopId) {
                            item.detailList.forEach(pro => {
                                recordList.push({
                                    id: pro.id,
                                    skuId: pro.productSkuSaleId,
                                    quantity: pro.quantity
                                })
                            })
                        }
                    });
                } else { //没店铺id，全部保存
                    list.forEach(item => {
                        item.detailList.forEach(pro => {
                            recordList.push({
                                id: pro.id,
                                skuId: pro.productSkuSaleId,
                                quantity: pro.quantity
                            })
                        })
                    });
                }

                this.setData({
                    shopcartList: list,
                    shopcartListForRecord: recordList,
                });

                //处理显示的商品数量
                let productList = this.data.productList;
                this.setData({
                    productList: this.dealProductSelect(productList),
                });
                this.dealShopcartSummary(0, 1);
            })
    },
    dealShopcartSummary(quantity, type = 0) { //计算购物车商品数量
        if(type == 1) {
            let summary = 0;
            this.data.shopcartList.forEach(item => {
                item.detailList.forEach(pro => {
                    summary = summary + pro.quantity;
                })
            });
            this.setData({
                shopcartNumber: summary,
            });
        } else {
            this.setData({
                shopcartNumber: this.data.shopcartNumber + quantity,
            });
            app.globalData.isRefreshShopcart = true;
        }
    },

    getFirstCategory() { //获取一级分类
        api.post('/product/category/one/list?shopId=' + this.data.shopId)
            .then(res => {
                this.setData({
                    firstCategoryList: res,
                    firstCategoryIndex: res.length ? res[0].id : -1,
                    noContent: false,
                    isFinished: false,
                });
                setTimeout(() => {
                    this.initScrollView();
                }, 500);

                if(res.length) {
                    this.getSecondCategory(res[0].id);
                } else {
                    this.setData({
                        productList: [],
                        pageNum: 1,
                        total: 0,
                        noContent: true,
                        isFinished: true,
                    });
                }
            })
    },
    initScrollView() { //初始化scrollview的宽度
        const query = wx.createSelectorQuery();
        query.select('#itemBox').boundingClientRect(res => {
            this.setData({
                baseDistance: res.width / 2,
                scrollLeft: 0
            });
            // console.log(this.data.baseDistance)
        }).exec();
    },

    getSecondCategory(id) { //获取二级分类
        api.post(`/product/category/next/list?currentId=${id}&shopId=${this.data.shopId}`)
            .then(res => {
                this.setData({
                    secondCategoryList: res,
                    secondCategoryIndex: res.length ? res[0].id : -1,
                    noContent: false,
                    isFinished: false,
                });
                if(this.data.secondCategoryIndex > -1) {
                    this.setData({
                        secondCategoryId: res[0].id,
                        productList: [],
                        pageNum: 1,
                        total: 0,
                    });
                    this.getProductList();
                } else {
                    this.setData({
                        productList: [],
                        pageNum: 1,
                        total: 0,
                        noContent: true,
                        isFinished: true,
                    });
                }
            })
    },
    getProductList() { //获取产品列表
        let params = {
            shopId: this.data.shopId,
            showTypeId: this.data.secondCategoryId,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post(`/product/list`, params)
            .then(res => {
                let list = res.content;
                list.forEach(item => {
                    item.quantity = 0;
                });
                let newList = [...this.data.productList, ...list];
                this.setData({
                    productList: this.dealProductSelect(newList),
                    total: res.total
                });

                //是否无内容标识
                if(this.data.productList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.productList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },
    dealProductSelect(list) { //初始化商品数量
        let dealList = list;
        let shopcartList = this.data.shopcartListForRecord;
        
        dealList.forEach(item => {
            let index = shopcartList.findIndex(i => {
                return i.skuId == item.id;
            });

            if(index > -1) {
                item.quantity = shopcartList[index].quantity;
            } else {
                item.quantity = 0;
            }
        });
        // console.log(dealList)
        return dealList;
    },
    loadMoreProduct() { //加载更多商品
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.getProductList();
            }, 800);
        }
    },

    //搜索商品
    gotoSearch() {
        wx.navigateTo({
            url: '/pages/storeCategorySearch/storeCategorySearch?id=' + this.data.shopId,
        });
    },

    //商品分类
    chooseFirstCategory(e) { //选择一级分类
        let index = e.currentTarget.dataset.index;
        let type = e.currentTarget.dataset.type;
        //计算标签距离左边的距离
        const query = wx.createSelectorQuery();
        query.select('#item'+index).boundingClientRect(res => {
            let self = res.width / 2; //自己中间的宽度
            let left = res.width * index; //距离左边的宽度
            let width = left + self; //总宽度

            if(width > this.data.baseDistance) { //比基准距离大，往左移
                this.setData({
                    scrollLeft: width - this.data.baseDistance,
                });
            } else if(width < this.data.baseDistance) { //比基准距离小，归零
                this.setData({
                    scrollLeft: 0
                });
            }
        }).exec();

        this.setData({
            firstCategoryIndex: this.data.firstCategoryList[index].id
        });
        this.getSecondCategory(this.data.firstCategoryList[index].id);

        if(type) {
            this.closeFirstCategory();
        }
    },
    chooseSecondCategory(e) { //选择二级分类
        this.setData({
            secondCategoryIndex: e.currentTarget.dataset.id,
            secondCategoryId: e.currentTarget.dataset.id,
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });

        this.getProductList();
    },

    //商品操作
    quantityPlus(e) { //数量加
        let index = e.currentTarget.dataset.index;
        let quantity = this.data.productList[index].quantity;

        if(quantity == 0) {
            //第一次选数量，添加购物车
            this.addShopcart(index);
        } else {
            //其他，修改购物车数量
            if(quantity >= this.data.productList[index].limitQuantity) {
                wx.showToast({
                    title: `该商品限购${this.data.productList[index].limitQuantity}件！`,
                    icon: 'none'
                });
                return;
            }
            
            this.dealShopcartQuantity(index, quantity);
        }
    },
    quantityMinus(e) { //数量减
        let index = e.currentTarget.dataset.index;
        if(this.data.productList[index].quantity == 1) {
            this.removeShopcart(index);
        } else {
            this.dealShopcartQuantity(index, -1);
        }
    },

    //购物车操作
    addShopcart(index, quantity = 0) { //添加购物车
        let params = {
            skuSaleId: this.data.productList[index].id
        }
        api.post('/order/cart/add', params)
            .then(res => {
                let list = this.data.shopcartListForRecord;
                list.push({
                    id: res,
                    skuId: this.data.productList[index].id,
                    quantity: quantity ? quantity : 1
                });
                this.setData({
                    shopcartListForRecord: list, //记录最新选择
                    [`productList[${index}].quantity`]: 1, //刷新数量
                });

                wx.showToast({
                    title: '添加购物车成功',
                    icon: 'none'
                });
                this.dealShopcartSummary(1);

                if(quantity > 1) { //添加时数量大于1，需进行下一步操作
                    this.dealShopcartQuantity(index, quantity-1);
                } else {
                    this.closeProductDetail();
                }
            })
    },
    dealShopcartQuantity(index, quantity = 1) { //修改购物车数量
        let list = this.data.shopcartListForRecord;
        let i = list.findIndex(item => {
            return item.skuId == this.data.productList[index].id
        })
        api.post(`/order/cart/quantity?id=${this.data.shopcartListForRecord[i].id}&diffQuantity=${quantity}`)
            .then(() => {
                list.forEach(item => {
                    if(item.skuId == this.data.productList[index].id) {
                        item.quantity = this.data.productList[index].quantity+ quantity;
                    }
                });
                this.setData({
                    shopcartListForRecord: list, //记录最新选择
                });
                
                this.setData({
                    [`productList[${index}].quantity`]: this.data.productList[index].quantity + quantity, //刷新数量
                });
                this.dealShopcartSummary(quantity);
                this.closeProductDetail();
            })
    },
    removeShopcart(index) { //删除购物车商品
        let list = this.data.shopcartListForRecord;
        let i = list.findIndex(item => {
            return item.skuId == this.data.productList[index].id
        });
        api.post(`/order/cart/remove?ids=${list[i].id}`)
            .then(() => {
                list.splice(i, 1);
                this.setData({
                    shopcartListForRecord: list, //记录最新选择
                    [`productList[${index}].quantity`]: 0, //刷新数量
                });

                wx.showToast({
                    title: '删除成功',
                    icon: 'none'
                });
                this.dealShopcartSummary(-1);
                this.closeProductDetail();
            })
    },
    gotoShopcart() { //查看购物车
        // wx.switchTab({
        //     url: '/pages/shopcart/shopcart',
        // });
        wx.navigateTo({
            url: '/pages/shopcartAll/shopcartAll',
        })
    },

    //弹窗操作
    openFirstCategory() { //打开一级分类弹窗
        animation1.top('0').step();
        this.setData({
            firstCategoryAnimation: animation1.export(),
            isShowAllFirstCategory: true,
            isShowLayer: true
        });
    },
    closeFirstCategory() { //关闭一级分类弹窗
        animation1.top('-100%').step();
        this.setData({
            firstCategoryAnimation: animation1.export(),
            isShowAllFirstCategory: false,
            isShowLayer: false,
            isPreview: false,
        });
    },

    //商品详情弹窗
    viewProductDetail(e) { //跳转商品详情
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/storeCategoryProduct/storeCategoryProduct?id=${id}&shopId=${this.data.shopId}`,
        });
    },
    openProductDetail(e) { //打开商品详情（停用）
        let id = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        animation2.bottom('0').step();
        this.setData({
            productDetailAnimation: animation2.export(),
            isShowProductDetail: true,
            isShowLayer: true
        });

        api.post(`/product/detail?id=${id}&shopId=${this.data.shopId}`)
            .then(res => {
                let item = res;
                item.originalQuantity = this.data.productList[index].quantity; //初始数量
                item.quantity = this.data.productList[index].quantity ? this.data.productList[index].quantity : 1; //显示数量
                item.selected = this.data.productList[index].quantity ? true : false; //是否已加入过购物车
                let content = util.formatRichText(res.productDesc);
                this.setData({
                    currentItem: item,
                    currentItemIndex: index,
                    productDesc: content,
                })
            })
    },
    closeProductDetail() { //关闭商品详情
        if(!this.data.isShowProductDetail) {
            return;
        }
        animation2.bottom('-100%').step();
        this.setData({
            productDetailAnimation: animation2.export(),
            isShowProductDetail: false,
            isShowLayer: false,
            isPreview: false,
        });
        setTimeout(() => {
            this.setData({
                currentItem: '',
            });
        }, 500);
    },
    previewImage(e) { //查看商品大图
        this.setData({
            isPreview: true, //防止页面刷新
        });
        let current = e.currentTarget.dataset.item;
        let url = this.data.currentItem.carouselImageList;
        wx.previewImage({
            current: current, //当前显示图片的http链接
            urls: url, // 需要预览的图片http链接列表
        });
    },
    closeLayer() { //点击遮罩层
        if(this.data.isShowAllFirstCategory) {
            this.closeFirstCategory();
        } else if(this.data.isShowProductDetail) {
            this.closeProductDetail();
        }
    },

    //商品详情操作
    toolbarQuantityPlus() { //数量加
        let number = this.data.currentItem.quantity;
        this.setData({
            [`currentItem.quantity`]: number + 1,
        });
    },
    toolbarQuantityMinus() { //数量减
        let number = this.data.currentItem.quantity;
        if(number == 0) {
            return;
        }
        this.setData({
            [`currentItem.quantity`]: number - 1,
        });
    },
    toolbarAddShopcart() { //加入购物车
        if(this.data.currentItem.originalQuantity == 0 && this.data.currentItem.quantity) {
            //第一次加购物车
            this.addShopcart(this.data.currentItemIndex, this.data.currentItem.quantity);
        } else if(this.data.currentItem.originalQuantity && this.data.currentItem.quantity == 0) {
            //删除购物车
            this.removeShopcart(this.data.currentItemIndex);
        } else if(this.data.currentItem.originalQuantity && this.data.currentItem.quantity != this.data.currentItem.originalQuantity) {
            //修改购物车数量
            this.dealShopcartQuantity(this.data.currentItemIndex, this.data.currentItem.quantity - this.data.currentItem.originalQuantity);
        } else {
            this.closeProductDetail();
        }
    },

    gotoChangeShop() { //切换店铺
        wx.navigateTo({
            // url: '/pages/storeList/storeList',
            url: `/pages/storeChange/storeChange?shopId=${this.data.shopId}&departmentId=${this.data.shopDetail.departmentId}`
        });
    },
    gotoShopDetail() { //查看店铺详情
        wx.navigateTo({
            url: '/pages/storeDetail/storeDetail?id=' + this.data.shopId,
        });
    },

    onShareAppMessage() {
        let path = '';
        if(this.data.shopId) {
            path = 'pages/storeCategory/storeCategory?id=' + this.data.shopId;
        } else {
            path = 'pages/index/index'
        }
        return {
            title: this.data.shopDetail.shopName ? this.data.shopDetail.shopName : '八桂小铺',
            desc: this.data.shopDetail.remark ? this.data.shopDetail.remark : '八桂小铺',
            path: path// 路径，传递参数到指定页面
        }
    }
})